package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.ExecutionDTO;
import com.sky.dto.ExecutionPageQueryDTO;
import com.sky.entity.Execution;
import com.sky.entity.ViolationRecord;
import com.sky.mapper.EmployeeMapper;
import com.sky.mapper.ExecutionMapper;
import com.sky.mapper.ViolationRecordMapper;
import com.sky.result.PageResult;
import com.sky.service.ExecutionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class ExecutionServiceImpl implements ExecutionService {
    @Autowired
    private ExecutionMapper executionMapper;
    @Autowired
    private ViolationRecordMapper violationRecordMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    //日志路径
    @Value("${execution.log.path:log/execution_log.txt}")
    private String LOG_FILE_PATH;
    @Override
    public PageResult pageQuery(ExecutionPageQueryDTO pageQuery) {
        //1、设置当前页和每页条数
        PageHelper.startPage(pageQuery.getPage(),pageQuery.getPageSize());
        Page<Execution> page =executionMapper.pageQuery(pageQuery);
        long total = page.getTotal();
        List<Execution> records = page.getResult();
        return new PageResult(total,records);
    }

    @Override
    @Transactional
    public void update(ExecutionDTO executionDTO) {
        Execution execution = new Execution();
        BeanUtils.copyProperties(executionDTO,execution);
        executionMapper.update(execution);
        writeExecutionLog("修改", BaseContext.getCurrentId());

    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        executionMapper.deleteBatch(ids);
        writeExecutionLog("删除", BaseContext.getCurrentId());
    }

    @Override
    @Transactional
    public void add(ExecutionDTO executionDTO) {
        //检测是否有违法记录新增时，如果有则自动复制字段到执行记录中，如果没有则手动通过executionDTO中的violationId来查询
        Execution execution = new Execution();
        ViolationRecord violationRecord = violationRecordMapper.getById(executionDTO.getViolationId());
        if (violationRecord==null){
            throw new RuntimeException("无此违法记录");
        }
        BeanUtils.copyProperties(violationRecord,execution);
        // 再手动设置 id 为 null（排除）
        execution.setId(null);
        execution.setViolationId(executionDTO.getViolationId());
        execution.setDetail(executionDTO.getDetail());
        execution.setFile(executionDTO.getFile());
        execution.setStatus(Execution.READED);
        executionMapper.insert(execution);
        writeExecutionLog("增加", BaseContext.getCurrentId());
    }
    public void writeExecutionLog(String operation, Long userId) {

        String logEntry = String.format("操作: %s, 操作人: %s, 时间: %s%n",
                operation, employeeMapper.getById(userId).getUsername(), LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));

        try (FileWriter writer = new FileWriter(LOG_FILE_PATH, true)) {
            writer.write(logEntry);
        } catch (IOException e) {
            // 处理写入异常，可以记录到日志系统
            log.error("写入日志失败", e);
        }
    }
}
